package com.mframework.mybatisfactory.mysql;

import com.mframework.mybatisfactory.TypeMap;

import java.util.Hashtable;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Mysql50SqlTypeMap implements TypeMap {

	private Map<String, String> map;
	private Map<String, String> regMap;
	private String sql;
	private String keyType;

	public Mysql50SqlTypeMap() {
		map = new Hashtable<String, String>();
		map.put("varchar", "String");
		map.put("nvarchar", "String");
		map.put("longtext", "String");
		map.put("text", "String");
		map.put("tinyint", "Integer");
		map.put("integer", "Integer");
		map.put("int", "Integer");
		map.put("number", "Integer");
		map.put("double", "Double");
		map.put("decimal", "Double");
		map.put("float", "Double");
		map.put("timestamp", "Date");
		map.put("datetime", "Date");
		map.put("date", "Date");
		map.put("bit", "Boolean");
		// 键值规则
		regMap = new Hashtable<String, String>();
		regMap.put("ID", "Long");
		regMap.put("\\w*_ID", "Long");
		sql = "select COLUMN_NAME as name,(IFNULL(CHARACTER_MAXIMUM_LENGTH,0)+IFNULL(NUMERIC_PRECISION,0)) as \"precision\""
				+ ",IFNULL(NUMERIC_SCALE,0) as scale,COLUMN_COMMENT as remark,DATA_TYPE as datatype from information_schema.COLUMNS"
				+ " where table_name='{tableName}' and TABLE_SCHEMA='{schema}'";
	}

	@Override
	public String getPropertyType(String columnName, String columnType, Integer precision, Integer scale) {
		// map查找
		String resultType = map.get(columnType.toLowerCase());
		// 正规表达式名字判断过滤
		for (String index : regMap.keySet()) {
			Pattern pattern = Pattern.compile(index, Pattern.CASE_INSENSITIVE);
			Matcher matcher = pattern.matcher(columnName);
			if (matcher.matches()) {
				resultType = regMap.get(index);
				break;
			}
		}
		// 匹配无效默认String
		if (resultType == null)
			resultType = "String";
		return resultType;
	}

	@Override
	public String getSql() {
		return sql;
	}
	public void setKeyType(String keyType){
		this.keyType=keyType;
		regMap.put("ID", keyType);
		regMap.put("\\w*_ID", keyType);
	}
	public String getKeyType(){
		return this.keyType;
	}
}
